import {adminStore} from '../store/admin'
const indexDb = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB

class IndexDbCache {
    public _db: IDBDatabase | null = null
    public _dbName: string = "ArgusDB_v3" // Changed DB Name to force recreation
    private _openPromise: Promise<any> | null = null

    constructor() {
        this.openDb()
    }

    openDb() {
        if (this._openPromise) {
            return this._openPromise
        }
        this._openPromise = new Promise((resolve, reject) => {
            const request = indexDb.open(this._dbName, 1) // Reset version to 1 for the new DB

            request.onerror = (e: any) => {
                console.error("IndexedDB error:", e.target.error)
                reject(e)
            }

            request.onsuccess = (e: any) => {
                this._db = e.target.result
                resolve(e)
            }

            request.onupgradeneeded = (e: any) => {
                this._db = e.target.result
                const storeList = ["list", "errorList"]
                storeList.forEach(storeName => {
                    if (!this._db!.objectStoreNames.contains(storeName)) {
                        this._db!.createObjectStore(storeName, {
                            keyPath: "id",
                            autoIncrement: true
                        })
                    }
                })
            }
        })
        return this._openPromise
    }

    async getDb() {
        if (!this._db) {
            await this.openDb()
        }
        return this._db!
    }

    closeDb() {
        this._db?.close()
    }

    async deleteData(storeName: string) {
        const db = await this.getDb()
        return new Promise((resolve, reject) => {
            const transaction = db.transaction(storeName, "readwrite")
            const store = transaction.objectStore(storeName)
            const response = store.clear()
            response.onsuccess = (e: any) => {
                resolve(e)
            }
            response.onerror = (e: any) => {
                reject(e)
            }
        })
    }

    async addData(storeName: string, data: any) {
        const db = await this.getDb()
        return new Promise((resolve, reject) => {
            const transaction = db.transaction(storeName, "readwrite")
            const store = transaction.objectStore(storeName)
            const response = store.add(data)
            response.onsuccess = (e: any) => {
                const admin_store = adminStore()
                admin_store.isOpenDrawer = true
                resolve(e.target.result)
            }
            response.onerror = (e: any) => {
                reject(e)
            }
        })
    }

    async getAllData(storeName: string) {
        const db = await this.getDb()
        return new Promise((resolve, reject) => {
            const transaction = db.transaction(storeName, "readonly")
            const store = transaction.objectStore(storeName)
            const response = store.getAll()
            response.onsuccess = (e: any) => {
                resolve(e.target.result)
            }
            response.onerror = (e: any) => {
                reject(e)
            }
        })
    }

    async countNum(storeName: string) {
        const db = await this.getDb()
        return new Promise((resolve, reject) => {
            const transaction = db.transaction(storeName, "readonly")
            const store = transaction.objectStore(storeName)
            const response = store.count()
            response.onsuccess = (e: any) => {
                resolve(e.target.result)
            }
            response.onerror = (e: any) => {
                reject(e)
            }
        })
    }
}

export default new IndexDbCache()